package com.goodfather.textbook.youdao.pad.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.goodfather.textbook.youdao.pad.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.security.MessageDigest;


/**
 * Created by PVer on 2017/5/15.
 */

public class ImageUtils {

    private static final String TAG = ImageUtils.class.getSimpleName();

    /**
     * 计算图片的缩放比例
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int width = options.outWidth;
        final int height = options.outHeight;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            //使用需要的宽高的最大值来计算比率
            final int suitedValue = reqHeight > reqWidth ? reqHeight : reqWidth;
            final int heightRatio = Math.round((float) height / (float) suitedValue);
            final int widthRatio = Math.round((float) width / (float) suitedValue);
            inSampleSize = heightRatio > widthRatio ? heightRatio : widthRatio;
            //用最大
        }
        return inSampleSize;
    }

    /**
     * 改变ImageView的亮度
     *
     * @param imageView
     * @param brightness
     */
    public static void changeLight(ImageView imageView, float brightness) {
        ColorMatrix cMatrix = new ColorMatrix();
        cMatrix.set(new float[]{
                brightness, 0, 0, 0, 0,
                0, brightness, 0, 0, 0,
                0, 0, brightness, 0, 0,
                0, 0, 0, 1, 0
        });
        imageView.setColorFilter(new ColorMatrixColorFilter(cMatrix));
    }

    public static void loadImage(String url, final int defaultRes, ImageView imageView) {
        Glide.with(C.get()).load(url)
                .apply(new RequestOptions()
                        .placeholder(defaultRes)
                        .priority(Priority.NORMAL)
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE))

                .into(imageView);

    }

    public static void loadImageWithoutCache(String url, final int defaultRes, ImageView imageView) {
        Glide.with(C.get()).load(url)
                .apply(new RequestOptions()
                        .placeholder(defaultRes)
                        .priority(Priority.NORMAL)
                        .diskCacheStrategy(DiskCacheStrategy.NONE))
                .into(imageView);

    }

    public static void loadImage(File file, final int defaultRes, ImageView imageView) {
        Glide.with(C.get()).load(file)
                .apply(new RequestOptions()
                        .placeholder(defaultRes)
                        .priority(Priority.NORMAL))
                .into(imageView);

    }

    public static void loadImage(byte[] bytes, final int defaultRes, ImageView imageView) {
        Glide.with(C.get()).load(bytes)
                .apply(new RequestOptions()
                        .placeholder(defaultRes)
                        .priority(Priority.NORMAL))
                .into(imageView);

    }


    public static void loadImage(String url, ImageView imageView) {
        Glide.with(C.get()).load(url).apply(new RequestOptions()
                .priority(Priority.NORMAL)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)).into(imageView);
    }

    public static void loadCircleImage(String url, ImageView imageView, int defaultImageRes) {
        Glide.with(C.get()).load(url)
                .apply(new RequestOptions()
                        .centerCrop()
                        .placeholder(defaultImageRes)
//                        .error(R.mipmap.ic_launcher)
                        .priority(Priority.NORMAL)
                        .transform(new GlideCircleTransform()))
                .into(imageView);
    }


    /**
     * 加载圆角图片
     *
     * @param url
     * @param imageView
     * @param cornerRadius 圆角半径
     */
    public static void loadCornerImage(String url, ImageView imageView, final int defaultRes, int cornerRadius) {
        Glide.with(C.get()).load(url)
                .apply(new RequestOptions()
                        .placeholder(defaultRes)
                        .priority(Priority.NORMAL)
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                        .transform(new GlideRoundTransform2(C.get(),cornerRadius))
                )
                .into(imageView);
    }

    public static void loadCornerImage(String url, ImageView imageView, int cornerRadius) {
        Glide.with(C.get()).load(url)
                .apply(new RequestOptions()
                        .placeholder(R.drawable.default_cover_video)
                        .priority(Priority.NORMAL)
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                        .transform(new GlideRoundTransform2(C.get(),cornerRadius))
                )
                .into(imageView);
    }


    public static void loadCornerImage(int imageResId, ImageView imageView, int cornerRadius) {
        Glide.with(C.get()).load(imageResId)
                .apply(new RequestOptions()
                        .placeholder(R.drawable.default_cover_video)
                        .priority(Priority.NORMAL)
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                        .transform(new GlideRoundTransform(cornerRadius))
                )
                .into(imageView);
    }


    public static void loadCornerImage(Context context, int imageResId, ImageView imageView, int cornerRadius) {
        Glide.with(C.get()).load(imageResId)
                .apply(new RequestOptions()
                        .placeholder(R.drawable.default_cover_video)
                        .priority(Priority.NORMAL)
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                        .transform(new GlideRoundTransform2(context, cornerRadius))
                )
                .into(imageView);
    }

    public static void loadCornerImage3(String url, ImageView imageView, int cornerRadius) {

        Glide.with(C.get()).load(url)
                .apply(RequestOptions.bitmapTransform(new RoundedCorners(cornerRadius))
                        .placeholder(R.drawable.default_cover_video)
                        .priority(Priority.NORMAL)
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE)).into(imageView);
    }


    public static void loadCover(Context context, String url,ImageView imageView) {

        Glide.with(context)
                .setDefaultRequestOptions(
                        new RequestOptions()
                                .frame(1000000)
                                .centerCrop()
                                .placeholder(R.drawable.default_cover_video)//可以忽略
                )
                .load(url)
                .into(imageView);
    }

    /**
     * 圆形图片的转换类
     */
    public static class GlideCircleTransform extends BitmapTransformation {

        public GlideCircleTransform() {
            super();
        }

        @Override
        public Bitmap transform(BitmapPool pool, Bitmap toTransform,
                                int outWidth, int outHeight) {
            return circleCrop(pool, toTransform);
        }

        private Bitmap circleCrop(BitmapPool pool, Bitmap source) {
            if (source == null) return null;
            int size = Math.min(source.getWidth(), source.getHeight());
            int x = (source.getWidth() - size) / 2;
            int y = (source.getHeight() - size) / 2;
            // TODO this could be acquired from the pool too
            Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
            Bitmap result = pool.get(size, size, Bitmap.Config.RGB_565);
            if (result == null) {
                result = Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565);
            }
            Canvas canvas = new Canvas(result);
            Paint paint = new Paint();
            paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
            paint.setAntiAlias(true);
            float r = size / 2f;
            canvas.drawCircle(r, r, r, paint);
            return result;
        }

        @Override
        public void updateDiskCacheKey(MessageDigest messageDigest) {

        }
    }


    /**
     * 显示圆角图片的转换类
     */
    public static class GlideRoundTransform extends BitmapTransformation {
        private float radius = 0f;

        public GlideRoundTransform() {
            this(4);
        }

        public GlideRoundTransform(int px) {
            super();
            this.radius = px;
        }

        @Override
        protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
            return roundCrop(pool, toTransform);
        }

        private Bitmap roundCrop(BitmapPool pool, Bitmap source) {
            if (source == null) return null;

            Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
            if (result == null) {
                result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
            }

            Canvas canvas = new Canvas(result);
            Paint paint = new Paint();
            paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
            paint.setAntiAlias(true);
            RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
            canvas.drawRoundRect(rectF, radius, radius, paint);
            return result;
        }

        @Override
        public void updateDiskCacheKey(MessageDigest messageDigest) {

        }
    }

    public static void setImageUri(ImageView view, Object src) {
        if (src instanceof Drawable) {
            view.setImageDrawable((Drawable) src);
        } else if (src instanceof Integer) {
            Glide.with((C.get())).load((int) src);
        } else if (src instanceof Uri) {
            Glide.with((C.get())).load((URI) src);
        } else if (src instanceof String) {
            String s = (String) src;
            if (PathUtil.isUrl(s)) {
                view.setImageURI(Uri.parse(s));
            } else if (PathUtil.isLocalPath(s)) {
                Glide.with((C.get())).load((String) src);
            } else {
                //do nothing
            }
        }
    }

    public static class GlideRoundTransform2 extends CenterCrop {

        private static float radius = 10f;

        public GlideRoundTransform2(Context context) {
            this(context, 10);
        }

        public GlideRoundTransform2(Context context, int px) {
            super(context);
            this.radius = px;
        }

        @Override
        protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
            //glide4.0+
            Bitmap transform = super.transform(pool, toTransform, outWidth, outHeight);
            return roundCrop(pool, transform);
            //glide3.0
            //return roundCrop(pool, toTransform);
        }

        private static Bitmap roundCrop(BitmapPool pool, Bitmap source) {
            if (source == null) return null;

            Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
            if (result == null) {
                result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
            }

            Canvas canvas = new Canvas(result);
            Paint paint = new Paint();
            paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
            paint.setAntiAlias(true);
            RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
            canvas.drawRoundRect(rectF, radius, radius, paint);
            return result;
        }

        public String getId() {
            return getClass().getName() + Math.round(radius);
        }

        @Override
        public void updateDiskCacheKey(MessageDigest messageDigest) {

        }
    }

    public static void saveAsFile(Bitmap bitmap, String filename) {
        FileOutputStream out = null;
        try {
            File file = new File(filename);
            if (!file.exists()) {
                file.createNewFile();
            }
            out = new FileOutputStream(filename);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
            // PNG is a lossless format, the compression factor (100) is ignored
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getImgName(String imgUrl) {
        if (imgUrl == null || imgUrl.equals("")) {
            return "";
        }
        String[] strs = imgUrl.split("/");
        return strs[strs.length - 1];
    }

}
